<template>
    <a-popover trigger="click">
        <a-button type="primary" size="small"
                 placeholder="選擇素材"
                 allow-clear
                 readonly
                  shape="round"
                 :style="{width:'120px'}"
                 @clear="emit('update:modelValue', '')"
        >
            <template #icon>
                <icon-plus />
            </template>
            <template #default>選擇素材</template>
        </a-button>

        <template #content>
            <div class="container" :class="{ 'is-list': !isGridView }">
                <a-row>
                    <section style="flex: 1; margin-right: 8px">
                        <a-input-group>
                            <a-select v-model="queryForm.type" size="small" :options="options" :style="{width:'160px'}" placeholder="全部" @change="search"/>
                        <a-input
                            v-model="searchValue"
                            placeholder="搜索图标名称"
                            allow-clear
                            size="small"
                            @input="search"
                            @clear="search"
                        >
                            <template #prefix>
                                <icon-search/>
                            </template>
                        </a-input>
                            </a-input-group>
                    </section>

                    <a-button size="small" @click="isGridView = !isGridView">
                        <template #icon>
                            <icon-apps v-if="isGridView"/>
                            <icon-unordered-list v-else/>
                        </template>
                    </a-button>
                </a-row>

                <section class="icon-list">
                    <a-row wrap :gutter="4">
                        <a-col v-for="(item,index) of fileList" :key="index" :span="isGridView ? 4 : 8">
                            <a-space size="mini" align="center">
                            <div class="icon-item" :class="{ active: modelValue === item.url }"
                                 @click="handleSelectedIcon(item)">
                                <img v-if="isImage(item.extension)"
                                     :preview="false"
                                     width="40"
                                     height="40"
                                     :src="item.url"
                                     show-loader
                                     class="file-image"/>
                                <GiSvgIcon v-else size="100%" :name="getFileImg(item)"></GiSvgIcon>
                                <div v-if="isImage(item.extension)" class="gi_line_1 icon-name">{{ item.name }}</div>
                            </div>
                            </a-space>
                        </a-col>
                    </a-row>
                </section>

                <a-row justify="center" align="center">
                    <div class="pagination">
                        <a-pagination size="mini" v-bind="pagination" show-total/>
                    </div>
                    <!--          <a-pagination-->
                    <!--            size="mini"-->
                    <!--            :page-size="pageSize"-->
                    <!--            :total="total"-->
                    <!--            :show-size-changer="false"-->
                    <!--            @change="onPageChange"-->
                    <!--          ></a-pagination>-->
                </a-row>
            </div>
        </template>
    </a-popover>
</template>

<script setup lang="ts">
import {useClipboard} from '@vueuse/core'
import {Message} from '@arco-design/web-vue'
import {type FileQuery, listFile} from "@/apis";
import {useTable} from '@/hooks'
import { FileIcon, ImageTypes } from '@/constant/file'
defineOptions({name: 'FileSelect'})
const paginationOption = reactive({
    defaultPageSize: 30,
    defaultSizeOptions: [30, 40, 50, 100, 120]
})
const queryForm = reactive<FileQuery>({
    sort: []
})
const {
    tableData: fileList,
    search,
    pagination,
} = useTable((page) => listFile({...queryForm, ...page}), {immediate: true, paginationOption})

const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    enableCopy: false
})
// 是否是图片类型文件
function isImage(exten){
    const extension = exten.toLowerCase()
    return ImageTypes.includes(extension)
}

// 是否是图片类型文件
function isVideo(exten){
    const extension = exten.toLowerCase()
    return ImageTypes.includes(extension)
}


// 获取文件图标，如果是图片就显示图片
function getFileImg (data) {
    const extension = data.extension.toLowerCase()
    if (ImageTypes.includes(extension)) {
        return data.url || ''
    }
    if (!Object.keys(FileIcon).includes(extension)) {
        return FileIcon['other']
    }
    return FileIcon[extension]
}

const options =   [
    {
        "label": "全部",
        "value": '0'
    },
    {
        "label": "圖片",
        "value": '2'
    },
    {
        "label": "視頻",
        "value": '4'
    }]

const emit = defineEmits(['select', 'update:modelValue'])

// 自定义图标模块
const SvgIconModules = import.meta.glob('@/assets/icons/*.svg')

interface Props {
    modelValue?: string
    enableCopy?: boolean
}

const searchValue = ref('') // 搜索词

// 图标列表
const isGridView = ref(false)
const iconList: string[] = []
for (const path in SvgIconModules) {
    const name = path.replace('/src/assets/icons/', '').replace('.svg', '')
    iconList.push(name)
}

const pageSize = 42
const current = ref(1)
const total = ref(iconList.length) // 图标总数

// 当前页的图标列表
const currentPageIconList = ref(iconList.slice(0, pageSize))
// 搜索列表
const searchList = ref<string[]>([])

// 页码改变
const onPageChange = (page: number) => {
    current.value = page
    if (!searchList.value.length) {
        currentPageIconList.value = iconList.slice((page - 1) * pageSize, page * pageSize)
    } else {
        currentPageIconList.value = searchList.value.slice((page - 1) * pageSize, page * pageSize)
    }
}

// 搜索
// const search = () => {
//     if (searchValue.value) {
//         const temp = searchValue.value.toLowerCase()
//         searchList.value = iconList.filter((item) => {
//             return item.toLowerCase().includes((temp))
//         })
//         total.value = searchList.value.length
//         currentPageIconList.value = searchList.value.slice(0, pageSize)
//     } else {
//         searchList.value = []
//         total.value = iconList.length
//         currentPageIconList.value = iconList.slice((current.value - 1) * pageSize, current.value * pageSize)
//     }
// }



// 点击选择图标
const handleSelectedIcon = async (icon) => {
    emit('select', icon.url)
    emit('update:modelValue', icon.url)
    if (props.enableCopy) {
        const {isSupported, copied, copy} = useClipboard()
        if (isSupported) {
            await copy(`<${icon} />`)
            if (copied) {
                Message.success(`已选择并且复制成功 ${icon} 图标`)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    width: 300px;
    overflow: hidden;

    .icon-list {
        margin-top: 10px;
        margin-bottom: 10px;

        .icon-item {
            height: 30px;
            margin-bottom: 4px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            border: 1px dashed var(--color-bg-1);

            .icon-name {
                display: none;
            }

            &.active {
                border: 1px dashed rgb(var(--primary-3));
                background-color: rgba(var(--primary-6), 0.05);
            }

            &:not(.active) {
                &:hover {
                    border-color: var(--color-border-3);
                }
            }
        }
    }
}

.is-list {
    min-width: 400px;

    .icon-list {
        height: 300px;
        overflow: hidden;
        overflow-y: auto;

        .icon-item {
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
            padding-left: 4px;
            box-sizing: border-box;

            .icon-name {
                margin-left: 6px;
                font-size: 12px;
                color: var(--color-text-2);
                display: block;
            }
        }
    }
}
</style>
